package studentdemo.dao;

import studentdemo.modul.Offer;
import studentdemo.util.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OfferDaoImpl implements OfferDao {
    @Override
    public int insertOffer(Offer offer) {
        String sql = "INSERT INTO Dujx_Offer11 (djx_Ocno11, djx_Oclno11) VALUES (?, ?)";
        try (Connection conn = DBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, offer.getOcno());
            ps.setString(2, offer.getOclno());
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int deleteOffer(String ocno, String oclno) {
        String sql = "DELETE FROM Dujx_Offer11 WHERE djx_Ocno11=? AND djx_Oclno11=?";
        try (Connection conn = DBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, ocno);
            ps.setString(2, oclno);
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public List<Offer> getOffersByCourse(String ocno) {
        String sql = "SELECT * FROM Dujx_Offer11 WHERE djx_Ocno11=?";
        List<Offer> list = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, ocno);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                list.add(new Offer(rs.getString("djx_Ocno11"), rs.getString("djx_Oclno11")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<Offer> getOffersByClass(String oclno) {
        String sql = "SELECT * FROM Dujx_Offer11 WHERE djx_Oclno11=?";
        List<Offer> list = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, oclno);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                list.add(new Offer(rs.getString("djx_Ocno11"), rs.getString("djx_Oclno11")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public List<Offer> getAllOffers() {
        String sql = "SELECT * FROM Dujx_Offer11";
        List<Offer> list = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection(); Statement st = conn.createStatement()) {
            ResultSet rs = st.executeQuery(sql);
            while (rs.next()) {
                list.add(new Offer(rs.getString("djx_Ocno11"), rs.getString("djx_Oclno11")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
} 